#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :fn_file.py
# @Time      :2024/11/9 0:51
# @Author    :zhou_yi

"""
   文件操作
"""
import asyncio
from PIL import Image
from pathlib import Path
import base64
import pandas as pd
from io import BytesIO
from settings import Root
from tools.units import FILE
from db.async_mongoDB import Gfs_point, Gfs_cwrs


#
# # 处理上传的图片(修改尺寸)
# def handle_image(b: bytes) -> bytes:
#     with BytesIO() as io_:
#         with BytesIO(b) as file_:
#             img = Image.open(file_)
#
#         img.resize(size=(500, 500))
#         img.save(io_, format='png')
#         img.close()
#         return io_.getvalue()
# 处理上传的图片(修改尺寸)

def handle_image(b: bytes) -> bytes:
    io_ = BytesIO()
    img = Image.open(BytesIO(b))
    img = img.resize(size=(500, 500))
    img.save(io_, format='png')
    img.close()
    return io_.getvalue()


# 正则查找word模板文件
def get_word_tpl_files(key: str, filemode='*') -> list[dict]:
    _path = Path(Root) / 'tpl'
    _res: list[dict] = FILE.re_get_files(path=_path,
                                         key=key,
                                         filemode=filemode)  # FILE.re_get_files('../tpl', '记录-清运')
    return _res


# 存储模版文件
def save_word_tpl_file_to_storage(b: bytes, save_name: str) -> bool:
    try:
        path = Path(Root) / f'tpl/{save_name}'
        with open(path, 'wb') as f:
            f.write(b)
        return True
    except:
        return False


# 读取上传的excel 文件
def handle_excel_data_file(b: bytes, sheet_name: str):
    io_ = BytesIO(b)
    df = pd.read_excel(io_, sheet_name=sheet_name, header=1)

    ...
    return True


# 点位图片文件存入数据库中 # 文件名:p-1001_idx.png
async def save_image_to_gfs_point(b, name: str):
    b = handle_image(b)
    res: tuple = await Gfs_point.put_file_by_name(b, name)
    return res


# 清运记录图片文件存入数据库中 文件名:pointID_f_y_m_d_idx.png
async def save_image_to_gfs_cwrs(b, name: str) -> tuple:
    b = handle_image(b)
    res: tuple = await Gfs_cwrs.put_file_by_name(b, name)
    return res


# 从点位集合中获取图片文件->bs64
async def get_image_from_gfs_point_by_name(file_name: str) -> bytes:
    _io: BytesIO = await Gfs_point.get_file_by_name(file_name)
    bs64 = base64.b64encode(_io.getvalue())
    return bs64


# 从清运记录集合中获取图片文件->bs64
async def get_image_from_gfs_cwrs_by_name(file_name: str) -> bytes:
    _io: BytesIO = await Gfs_point.get_file_by_name(file_name)
    bs64 = base64.b64encode(_io.getvalue())
    return bs64


if __name__ == '__main__':
    # print(get_word_tpl_files('三方比价_有害垃圾'))

    ...
